package com.beerandjesus.photogallery.page;

import com.beerandjesus.photogallery.PhotoGalleryException;
import com.beerandjesus.photogallery.image.PhotoGalleryImage;
import com.beerandjesus.photogallery.image.PhotoGalleryImageListImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Factory for configuring any given page in a Beer and Jesus photo
 * gallery.
 * <p/>
 * This factory is initialized with a complete image list in the
 * request directory once, and provides a PhotoGalleryPage on a
 * request by request basis thereafter.
 */
public class PhotoGalleryPageFactory {
    private String pageTitle;
    private String baseDir;
    private int photosPerPage;
    private List<PhotoGalleryImage> list;
    private final Object lock = new Object();
    private ListPagingStrategy pagingStrategy;
    private String pageDescription;

    public PhotoGalleryPageFactory(String baseDir, int photosPerPage, ListPagingStrategy strategy) {
        this.baseDir = baseDir;
        this.photosPerPage = photosPerPage;
        this.pagingStrategy = strategy;
    }

    public PhotoGalleryPage getPage(HttpServletRequest request) throws PhotoGalleryException {
        if (list == null) {
            synchronized (lock) {
                if (list == null) {
                    PhotoGalleryImageListImpl imageList = new PhotoGalleryImageListImpl(baseDir);
                    list = imageList.getList(request);
                }
            }
        }
        PhotoGalleryPage page = new PhotoGalleryPageImpl(request, list, pagingStrategy, photosPerPage);
        page.setTitle(pageTitle);
        page.setDescription(pageDescription);
        return page;
    }

    public void setPageTitle(String pageTitle) {
        this.pageTitle = pageTitle;
    }

    public void setBaseDir(String baseDir) {
        this.baseDir = baseDir;
    }

    public void setPhotosPerPage(int photosPerPage) {
        this.photosPerPage = photosPerPage;
    }

    public void setPagingStrategy(ListPagingStrategy pagingStrategy) {
        this.pagingStrategy = pagingStrategy;
    }

    public void setPageDescription(String pageDescription) {
        this.pageDescription = pageDescription;
    }
}
